﻿#include "sysdiccontroller.h"
#include "utils/dictionaryutil.h"

SysDicController::SysDicController()
{
    m_pHelper = SqlHelper::instance();

    m_mapFunc.insert("/sys/dic/getdic",     &SysDicController::getDic);     //获取字典
    m_mapFunc.insert("/sys/dic/datagrid",   &SysDicController::datagrid);   //获取数据字典列表
    m_mapFunc.insert("/sys/dic/save",       &SysDicController::save);       //保存数据字典
    m_mapFunc.insert("/sys/dic/saveval",    &SysDicController::saveVal);    //保存字典值
    m_mapFunc.insert("/sys/dic/delete",     &SysDicController::delDic);     //删除字典
}

void SysDicController::service(HttpRequest& request, HttpResponse& response)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));
    QString access_token = request.getParameter("access_token");
    QString username = JwtUtil::getUsername(access_token);
    if(username == NULL || username.isEmpty())
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }
    SysUser visitUser;
    if(!m_pHelper->selectUserByName(visitUser, username))
    {
        ret.failedMsg(QStringLiteral("用户不存在，操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    QByteArray path = request.getPath().toLower();
    if(m_mapFunc.contains(path))
    {
        pServFunc func = m_mapFunc.value(path);
        (this->*func)(request, response, visitUser);
    }
}

//获取字典
//http://localhost:9004/sys/dic/getDic?parentId=?&access_token=?
//{"code":0,"data":{"code":"dept_type","createDate":1552210546000,"createName":"system","id":"?","memo":"","name":"部门类型","updateDate":1692329064000,"updateName":"admin","versions":1},"msg":""}
void SysDicController::getDic(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));

    QString parentId = request.getParameter("parentId");
    int dicId = parentId.split("_")[0].toInt();

    SysDictionary dic;
    dic.setId(dicId);
    m_pHelper->selectEntityById(&dic);

    QJsonObject obj;

    obj.insert("id", parentId);
    obj.insert("version", dic.getVersion());
    obj.insert("createName", dic.getCreateName());
    obj.insert("createDate", dic.getCreateDate().toMSecsSinceEpoch());
    obj.insert("updateName", dic.getUpdateName());
    obj.insert("updateDate", dic.getUpdateDate().toMSecsSinceEpoch());

    obj.insert("code", dic.getCode());
    obj.insert("name", dic.getName());
    obj.insert("memo", dic.getMemo());


    ret.setData(obj);
    ResponseUtil::replyJson(response, ret);

}

//获取数据字典列表
//http://localhost:9004/sys/dic/datagrid?name=?&&access_token=?
//{"code":0,"count":65,"data":[{"id":"?","memo":"","name":"部门类型","parentId":"-1","value":"dept_type"},
//{"id":"?","memo":"","name":"集团","parentId":"1","value":"0"},{"id":"2","memo":"","name":"公司","parentId":"1","value":"1"}],"msg":""}
void SysDicController::datagrid(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    QString name = request.getParameter("name");

    QStringList condi;
    condi << "name like '%" + name + "%'";

    QList<SysDictionary> dicList;
    m_pHelper->getDictList(dicList, condi, "");

    QStringList tmp;
    QList<SysDicValue> valueList;
    m_pHelper->getDictValueList(valueList, tmp, "");

    QJsonArray dataArray;

    //ID采用下划线分割
    //父节点ID XX_0
    //子节点ID XX_1
    foreach (SysDictionary dic, dicList) {
        int dicId = dic.getId();
        QJsonObject dicObj;
        dicObj.insert("id", QString("%1_0").arg(dicId));
        dicObj.insert("name", dic.getName());
        dicObj.insert("value", dic.getCode());
        dicObj.insert("memo", dic.getMemo());
        dicObj.insert("parentId", "-1");
        dataArray.append(dicObj);

        foreach (SysDicValue value, valueList)
        {
            if(value.getParentId() == dicId)
            {
                QJsonObject dicVObj;
                dicVObj.insert("id", QString("%1_%2").arg(dicId).arg(value.getId()));
                dicVObj.insert("name", value.getLabel());
                dicVObj.insert("value", value.getValue());
                dicVObj.insert("memo", "");
                dicVObj.insert("parentId", QString("%1_0").arg(value.getParentId()));
                dataArray.append(dicVObj);
            }
        }
    }

    ResultJson ret(0, true, QStringLiteral(""));
    ret.setProp("count", dicList.size() + valueList.size());
    ret.setData(dataArray);
    ResponseUtil::replyJson(response, ret);
}

//保存数据字典
//http://localhost:9004/sys/dic/save
//{"code":0,"success":true,"msg":"操作成功","data":null}
/*
id: 1_0
name: 普通性别
code: common_sex
memo:
access_token: ?
*/
void SysDicController::save(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));
    SysDictionary dic;

    dic.setName(request.getParameter("name"));
    dic.setCode(request.getParameter("code"));
    dic.setMemo(request.getParameter("memo"));

    QString idParam = request.getParameter("id");

    //编辑字典
    if(!idParam.isEmpty())
    {
        int dicId = idParam.split("_")[0].toInt();
        dic.setId(dicId);
        dic.setUpdateDate(QDateTime::currentDateTime());
        dic.setUpdateName(visitUser.getUserName());

        if(!m_pHelper->updateEntity(&dic))
        {
            ret.failedMsg(QStringLiteral("操作失败"));
        }
    }
    //新增字典
    else
    {
        //保存字典
        dic.setCreateDate(QDateTime::currentDateTime());
        dic.setCreateName(visitUser.getUserName());
        dic.setUpdateDate(QDateTime::currentDateTime());
        dic.setUpdateName(visitUser.getUserName());
        dic.setVersion(1);

        if(!m_pHelper->insertEntity(&dic))
        {
            ret.failedMsg(QStringLiteral("操作失败"));
        }
    }
    DictionaryUtil::instance()->initDictionary();
    ResponseUtil::replyJson(response, ret);

    QJsonObject objParam = request.getParameterJson();
    objParam.insert("access_token", "?");
    SysLog log("system", SysLog::SAVE, QStringLiteral("保存字典"),
               visitUser.getUserName(),
                QString(__FILE__),
                QString(__FUNCTION__),
                GlobalFunc::JsonToString(objParam),
                request.getPeerAddress().toString(),
                request.getHeader("User-Agent"),
                QStringLiteral("保存字典成功"));
    m_pHelper->insertEntity(&log);

}

//保存字典值
//http://localhost:9004/sys/dic/saveval
//{"code":0,"success":true,"msg":"操作成功","data":null}
/*
parentId: 1_10
id: 1
label: 集团
value: 0
access_token: ?
*/
void SysDicController::saveVal(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{

    ResultJson ret(0, true, QStringLiteral("操作成功"));
    SysDicValue dicV;

    dicV.setLabel(request.getParameter("label"));
    dicV.setValue(request.getParameter("value"));
    QString parentIdParam = request.getParameter("parentId");
    dicV.setParentId(parentIdParam.split("_")[0].toInt());

    QString idParam = request.getParameter("id");

    //编辑字典值
    if(!idParam.isEmpty() && idParam.split("_").size() == 2)
    {
        int dicVId = idParam.split("_")[1].toInt();
        dicV.setId(dicVId);
        dicV.setUpdateDate(QDateTime::currentDateTime());
        dicV.setUpdateName(visitUser.getUserName());

        if(m_pHelper->updateEntity(&dicV))
        {
            ResponseUtil::replyJson(response, ret);
            DictionaryUtil::instance()->initDictionary();
            return;
        }
    }
    //新增字典值
    else
    {
        //保存字典值
        dicV.setCreateDate(QDateTime::currentDateTime());
        dicV.setCreateName(visitUser.getUserName());
        dicV.setUpdateDate(QDateTime::currentDateTime());
        dicV.setUpdateName(visitUser.getUserName());
        dicV.setVersion(1);

        if(m_pHelper->insertEntity(&dicV))
        {
            ResponseUtil::replyJson(response, ret);
            DictionaryUtil::instance()->initDictionary();
            return;
        }
    }
    ret.failedMsg(QStringLiteral("操作失败"));
    ResponseUtil::replyJson(response, ret);

    QJsonObject objParam = request.getParameterJson();
    objParam.insert("access_token", "?");
    SysLog log("system", SysLog::SAVE, QStringLiteral("保存字典值"),
               visitUser.getUserName(),
                QString(__FILE__),
                QString(__FUNCTION__),
                GlobalFunc::JsonToString(objParam),
                request.getPeerAddress().toString(),
                request.getHeader("User-Agent"),
                QStringLiteral("保存字典值成功"));
    m_pHelper->insertEntity(&log);
}

//删除字典
//http://localhost:9004/sys/dic/delete
//{"code":0,"success":true,"msg":"操作成功","data":null}
/*
id: 1_1
parentId: 1 或者 -1
access_token: ?
*/
void SysDicController::delDic(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));
    QString idParam = request.getParameter("id");
    if(idParam.isEmpty())
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    int parentId = request.getParameter("parentId").toInt();

    //删除字典值
    if(parentId > 0)
    {
        int dicVId = idParam.split("_")[1].toInt();
        SysDicValue dicv;
        dicv.setId(dicVId);
        if(!m_pHelper->deleteEntity(&dicv))
        {
            ret.failedMsg(QStringLiteral("操作失败"));
        }
    }
    //删除字典
    else
    {
        int dicId = idParam.split("_")[0].toInt();
        SysDictionary dic;
        dic.setId(dicId);
        if(!m_pHelper->deleteEntity(&dic))
        {
            ret.failedMsg(QStringLiteral("操作失败"));
        }

        //同时也删除字典值
        QStringList condi;
        condi << "parent_id=" + dicId;

        QList<SysDicValue> valueList;
        m_pHelper->getDictValueList(valueList, condi, "");
        foreach(SysDicValue dicv,  valueList)
        {
            m_pHelper->deleteEntity(&dicv);
        }

    }
    DictionaryUtil::instance()->initDictionary();
    ResponseUtil::replyJson(response, ret);

    QJsonObject objParam = request.getParameterJson();
    objParam.insert("access_token", "?");
    SysLog log("system", SysLog::DEL, QStringLiteral("删除字典"),
               visitUser.getUserName(),
                QString(__FILE__),
                QString(__FUNCTION__),
                GlobalFunc::JsonToString(objParam),
                request.getPeerAddress().toString(),
                request.getHeader("User-Agent"),
                QStringLiteral("删除字典成功"));
    m_pHelper->insertEntity(&log);
}
